 //demo中的数据是模拟状态数据，用于测试，实际使用中，请根据您自己的业务编写
import Vue from 'vue'
import Vuex from 'vuex'
import URL from '../api/url.js';
import { login,getUserInfo,updateUserInfo,getFriendList,getGroup } from 'api/user';
import WebSocket from '@/common/websocket.js';


const USER_KEY = 'userInfo';
const TOKEN_KEY = 'token';


Vue.use(Vuex)
const store = new Vuex.Store({
    state: {
		worldBackgroudImage:uni.getStorageSync('worldBg')||'/static/icon/bg-2.jpg',//空间的背景
		lastUserId:uni.getStorageSync('lastUser') || -1,
		token: uni.getStorageSync(TOKEN_KEY) || '',
		userInfo: uni.getStorageSync(USER_KEY) || {},
		//对话
		sessions: uni.getStorageSync('sessions')|| [],
		//好友列表
		friendList: uni.getStorageSync('friendList')||[],
		//记录当前聊天的会话号
		sessionIndex:-1,
		//weoskcet状态
		webSocket: {
			isSocketOpen:false, //连接状态
			url:URL.getWebsokcetUrl(),//服务器地址
			pingpongTime:'',     //心跳
		},
		//搜索的列表
		searchPeople:[],
		searchGroups:[],
		keyword:'',
		///申请列表
		applyList:uni.getStorageSync('applyList')|| [],
		//大厅聊天
		lobbyMessages:{
			unchecked:0,
			messages:[], //实际的消息
			showMessages:[], //应该显示的消息
			lastTime:'',
			lastMessage:'',
			online:0,
			
		},
		//群聊
		groupList : uni.getStorageSync('groupList')||[]
	},
    mutations: {
		setWorldBg(state,url){
			state.worldBackgroudImage = url;
		},
		addLobbyMessages(state,messages){
			state.lobbyMessages.messages = messages;
		},
		addLobbyMessage(state,message){
			state.lobbyMessages.messages.push(message);
		},
		addLobbyShowMessage(state,message){
			state.lobbyMessages.showMessages.push(message);
		},
		addApply(state,apply){
			state.applyList.unshift(apply);
		},
		setSessionIndex(state,i){
			state.sessionIndex = i;
		},
		setSession(state,session){
			state.sessions = session;
		},
		setUserInfo(state, user){
			state.userInfo = user;
		},
        setNickname(state, name){
			state.userInfo.nickname = name;
		},
		setSignature(state, sig){
			state.userInfo.signature = sig;
		},
		setGender(state, sex){
			state.userInfo.gender = sex;
		},
		setToken(state, token){
			state.token = token;
		},
		setAvatar(state, url){
			state.userInfo.avatar = url;
		},
		setLoginId(state, lid){
			state.userInfo.loginId = lid;
		},
		setFriendList(state,list){
			state.friendList = list;
		},
		setLastUser(state,last){
			state.lastUserId = last;
		},
		setGroupList(state,groups){
			state.groupList = groups;
		}
    },
    actions: {
		//设置世界背景
		setWorldBg(context,url){
			uni.setStorage({
				key:'worldBg',
				data: url
			})
			this.commit('setWorldBg',url);
			uni.showToast({
				title:'更换成功',
				icon:'success'
			})
		},
		//获取群
		async getGroupList(context){
			const { content: res } = await getGroup({
				token:this.getters.token
			});
			uni.setStorage({
				key:'groupList',
				data: res
			})
			this.commit('setGroupList',res);
		},
		receiveLobbyMessage(context,lastMessage){
			this.state.lobbyMessages.lastTime = lastMessage.time;
			if(lastMessage.msgType=='text'){
				this.state.lobbyMessages.lastMessage = lastMessage.nickname+' : '+lastMessage.content;
			}else{
				this.state.lobbyMessages.lastMessage = lastMessage.nickname+' : 【图片】';
			}
			this.commit('addLobbyMessage',lastMessage);
			if(this.state.sessionIndex!=-2){
				this.state.lobbyMessages.unchecked++;
			}else{
				setTimeout(()=>{
					uni.pageScrollTo({
						scrollTop:999999999999999
					})
				},50);
				this.commit('addLobbyShowMessage',lastMessage);//展示的消息同步显示
			}
			
		},
		receiveLobbyMessages(context,rawMessages){
			let messages = [];
			for(let i=0;i<rawMessages.length;i++){
				messages.push(JSON.parse(rawMessages[i]));
			}
			if(messages.length!=0){
				let lastMessage = messages[messages.length-1];
				this.state.lobbyMessages.lastTime = lastMessage.time;
				if(lastMessage.msgType=='text'){
					this.state.lobbyMessages.lastMessage = lastMessage.nickname+' : '+lastMessage.content;
				}else{
					this.state.lobbyMessages.lastMessage = lastMessage.nickname+' : 【图片】';
				}
				this.commit('addLobbyMessages',messages);
			}
		},
		///收到了新的申请
		receiveApply(content,data){
			let applies = this.getters.applyList;
			if(data.type=='invite-group'||data.type=='group-apply'){
				console.log(213212)
				for(let i=0;i<applies.length;i++){
					if(applies[i].from.id==data.from.id&&applies[i].group.id==data.group.id&&applies[i].type==data.type)
					{
						return;
					}
				}
			}
			
			else{
				for(let i=0;i<applies.length;i++){
					if(applies[i].from.id==data.from.id&&applies[i].type==data.type)
					{
						return;
					}
				}
			}
			console.log('插入')
			//先检查是否已经有了
			this.commit('addApply',data);
			applies = this.getters.applyList;
			//本地保存申请信息
			uni.setStorage({
				key:'applyList',
				data: applies
			})
		},
		//同意好友申请
		addFriend(context,person){
			this.state.friendList.unshift(person);
			//本地保存会话
			uni.setStorage({
				key:'friendList',
				data: this.state.friendList
			})
		},
		//根据用户id查询好友的信息
		getFriendInfoById(context,id){
			let list = this.state.friendList;
			for(let i=0;i<list.length;i++){
				if(list[i].id==id){
					return list[i];
				}
			}
			return 'not found';
		},
		//根据用户id查询群聊的信息
		getGroupInfoById(context,id){
			let list = this.state.groupList;
			for(let i=0;i<list.length;i++){
				if(list[i].id==id){
					return list[i];
				}
			}
			return 'not found';
		},
		//发送消息
		sendMessageOut(context,data){
			let index = data.index;
			let content = data.content;
			let type = data.type;
			let time = data.time;
			let message = {
				content:content,
				type:type,
				time:time,
				to:'out',
				from:this.getters.user.id,
				avatar:this.getters.user.avatar,
				nickname:this.getters.user.nickname
			}
			this.state.sessions[index].messages.push(message);
			this.state.sessions[index].lastTime = time;
			let t;
			if(data.msgType=='group'){
				this.state.sessions[index].lastMessage=type=='text'?this.getters.user.nickname+':'+content:'【图片】';
			}else{
				this.state.sessions[index].lastMessage = type=='text'?content:'【图片】';
			}
			setTimeout(()=>{
				uni.pageScrollTo({
					scrollTop: 99999999999,    //滚动到页面的目标位置（单位px）
				});
			},10);
		},
		
		//收到消息
		receiveMessage(context,data){
			let index = data.index;
			let content = data.content;
			let type = data.type;
			let time = data.time;
			let message = {
				content:content,
				type:type,
				time:time,
				to:'in',
				from:data.from,
				avatar:data.avatar,
				nickname:data.nickname
			}
			this.state.sessions[index].messages.push(message);
			this.state.sessions[index].lastTime = time;
			if(data.msgType=='group'){
				this.state.sessions[index].lastMessage = type=='text'?data.nickname+':'+data.content:data.nickname+':'+'【图片】';
			}else{
				this.state.sessions[index].lastMessage = type=='text'?content:'【图片】';
			}
			//如果用户不在当前房间 则未读消息++
			if(this.state.sessionIndex!=index){
				this.state.sessions[index].unchecked++;
			}else{
				setTimeout(()=>{
					uni.pageScrollTo({
						scrollTop:999999999999999
					})
				},50)
			}
			
			if(this.state.sessionIndex==-1){
				this.dispatch('sortSessionByTime');
			}
			this.dispatch('saveMessage');
		},
		//保存聊天记录
		saveMessage(){
			let sessions = this.getters.sessions;
			//本地保存会话
			uni.setStorage({
				key:'sessions',
				data: sessions
			})
		},
		//当向某个会话发消息时，会话置顶，否则退出时啥也不做
		reRangeSession(context,index){
			let sessions = this.getters.sessions;
			let session = sessions[index];
			sessions.splice(index,1);
			sessions.unshift(session);
			this.commit('setSession',sessions);
			//本地保存会话
			uni.setStorage({
				key:'sessions',
				data: sessions
			})
		},
		//以用户id获取对话的房间号
		getRoomIndex(context,id){
			let sessions = this.getters.sessions;
			for(let i=0;i<sessions.length;i++){
				if(sessions[i].id==id){
					return i;
				}
			}
			return -1;
		},
		//删除好友申请
		deleteApply(context,index){
			let applies = this.getters.applyList;
			applies.splice(index,1);
			this.state.applyList = applies;
			//本地保存
			uni.setStorage({
				key:'applyList',
				data: applies
			})
		},
		//删除好友by id
		deleteFriendById(context,id)
		{
			let friends = this.state.friendList;
			for(let i=0;i<friends.length;i++){
				if(friends[i].id==id){
					this.dispatch('deleteFriend',i);
					break;
				}
			}
		},
		//删除好友
		deleteFriend(context,index){
			let friend = this.state.friendList[index];
			let i = this.dispatch('getRoomIndex',friend.id);
			if(i!=-1){
				// /删除会话
				this.dispatch('removeSessionById',friend.id);
			}
			//删除好友
			this.state.friendList.splice(index,1);
			uni.setStorage({
				key:'friendList',
				data: this.state.friendList
			})
		},
		//删除会话byId
		removeSessionById(context,id){
			let sessions = this.getters.sessions;
			for(let i=0;i<sessions.length;i++){
				if(sessions[i].id==id){
					sessions.splice(i,1);
					break;
				}
			}
			this.commit('setSession',sessions);
			//本地保存会话
			uni.setStorage({
				key:'sessions',
				data: sessions
			})
		},
		//删除会话
		removeSession(context,index){
			let sessions = this.getters.sessions;
			sessions.splice(index,1);
			this.commit('setSession',sessions);
			//本地保存会话
			uni.setStorage({
				key:'sessions',
				data: sessions
			})
		},
		//创建新的会话
		async createNewChatRoom(context,data){
			let sessions = this.getters.sessions;
			let session = {
				id: data.id,
				unchecked: 0,
				name:data.nickname,
				messages: [],
				avatar: data.avatar,
				lastTime: data.time,
				lastMessage: ''
			}
			sessions.push(session);
			this.commit('setSession',sessions);
			await this.dispatch('sortSessionByTime');
		},
		//聊天排序
		sortSessionByTime(){
			let sessions = this.getters.sessions;
			for(let i=0;i<sessions.length-1;i++){
				for(let j=i+1;j<sessions.length;j++){
					if(new Date(sessions[i].lastTime) < new Date(sessions[j].lastTime)){
						let t = sessions[i];
						sessions[i] = sessions[j];
						sessions[j] = t;
					}
				}
			}
			this.commit('setSession',sessions);
			//本地保存会话
			uni.setStorage({
				key:'sessions',
				data: sessions
			})
		},
		setAndStoreToken(context,token){
			//本地保存token
			uni.setStorage({
				key:TOKEN_KEY,
				data: token
			})
			this.commit('setToken',token);
		},
		//退出登录
		clearUserInfo(){
			//清除token
			this.commit('setToken','');
			uni.clearStorage(TOKEN_KEY);
			uni.closeSocket();//关闭websocket
		},
		// 登录
		async setUserInfo(context,token) {
		  const { content: res } = await getUserInfo({
			 token:token
		  });
		  
		  // 解析后端传送过来的json对象
		  // 保存到vuex中，通过commit
		  let user = {
			  id : res.id,
			  loginId : res.loginId,
			  nickname : res.nickname,
			  gender : res.gender || '未设置',
			  signature : res.signature || '未设置',
			  avatar : res.avatar || 'https://s2.loli.net/2022/05/04/gWjFMmZxJIbsz7G.png',
			  register_time: res.registerTime
		  }
		  
		  
		  //本地保存用户信息
		  uni.setStorage({
		  	key:USER_KEY,
		  	data: user
		  })
		  this.commit('setUserInfo',user);
		
		   
		  // 获取好友列表
		  this.dispatch('setFriendList');
		  //获取群聊列表
		  this.dispatch('getGroupList');
		  
		  uni.setStorage({
		  	key:'lastUser',
		  	data: res.id
		  })
		  
		  
		  //如果不是上次登录的用户的话 需要删除会话
		  if(res.id!=this.state.lastUserId){
			  console.log(res.id+"<----"+this.state.lastUserId+'\n用户变更,清除本地记录')
			  let sessions = [];
			  //本地保存会话
			  uni.setStorage({
			  	key:'sessions',
			  	data: sessions
			  })
			  this.commit('setSession',sessions);
			  //清空
			  this.state.applyList = [];
			  uni.setStorage({
			  	key:'applyList',
			  	data: []
			  })
			  //覆盖记录
			  	uni.setStorage({
			  		key:'friendList',
			  		data: this.state.friendList
			  	})
		  }
		  ///连接websokct
		  //WebSocket.connectSocketInit();
		
		},
		// 获取好友列表
		async setFriendList(context) {
		const { content: res } = await getFriendList({
			 token:this.getters.token
		  });
		  // 解析后端传送过来的json对象
		  // console.log(res);
		  // 保存到vuex中，通过commit
		  //本地保存用户信息
		  uni.setStorage({
		  	key:'friendList',
		  	data: res
		  })
		  this.commit('setFriendList',res);
		},
		// 更新昵称
		updateNickname(context,name) {
		  // 保存到vuex中，通过commit
		  this.commit('setNickname',name);
		  //本地保存用户信息
		  uni.setStorage({
		  	key:USER_KEY,
		  	data: this.getters.user
		  })
		  
		},
		// 更新性别
		updateGender(context,sex) {
		  // 保存到vuex中，通过commit
		  this.commit('setGender',sex);
		  //本地保存用户信息
		  uni.setStorage({
		  	key:USER_KEY,
		  	data: this.getters.user
		  })
		},
		// 更新个性签名
		updateSignature(context,sig) {
		  // 保存到vuex中，通过commit
		  this.commit('setSignature',sig);
		  //本地保存用户信息
		  uni.setStorage({
		  	key:USER_KEY,
		  	data: this.getters.user
		  })
		},
		// 更新头像
		updateAvatar(context,url) {
		  // 保存到vuex中，通过commit
		  this.commit('setAvatar',url);
		  //本地保存用户信息
		  uni.setStorage({
		  	key:USER_KEY,
		  	data: this.getters.user
		  })
		},
    },
    getters:{
		worldBg(state){
			return state.worldBackgroudImage;
		},
		sessionIndex(state){
			return state.sessionIndex;
		},
		groups(state){
			return state.groupList;
		},
		lobbyMessages(state){
			return state.lobbyMessages;
		},
		applyList(state){
			return state.applyList;
		},
		isSocketOpen(state){
			return state.webSocket.isSocketOpen;
		},
		friends(state){
			return state.friendList;
		},
		sessions(state){
			return state.sessions;
		},
		user(state){
			return state.userInfo;
		},
        id(state){
			return state.userInfo.loginId;
		},
		nickname(state){
			return state.userInfo.nickname;
		},
		avatar(state){
			return state.userInfo.avatar;
		},
		gender(state){
			return state.userInfo.gender;
		},
		token(state){
			return state.token;
		}
    }
})
export default store